<?php

namespace SDK;

use Exception;


class Client {
    public $app_id;
    public $app_secret;
    public $base_url;

    public function __construct($app_id, $app_secret, $base_url) {
        $this->app_id = $app_id;
        $this->app_secret = $app_secret;
        $this->base_url = $base_url;
    }

    public static function newClient($app_id, $app_secret, $base_url) {
        return new self($app_id, $app_secret, $base_url);
    }

    public function post($endpoint, $post_params) {
        $url = $this->base_url . $endpoint;
        
        if (!function_exists('curl_init')) {
            die('cURL方法调用失败!');
        }
        $ch = curl_init();
        $fpp =  json_encode($post_params);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // 返回响应而不是直接输出
        curl_setopt($ch, CURLOPT_POST, true);  // 设置请求方式为 POST
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); // 暂时禁用验证 todo 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fpp);  // 设置 POST 数据
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",  // 设置请求头
        ]);
        $response = curl_exec($ch);
        if ($response === false) {
            throw new Exception('请求失败: ' . curl_error($ch));
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception('请求失败，HTTP 状态码: ' . $httpCode.' ；返回内容:'.$response);
        }
        curl_close($ch);
        $resf = json_decode($response, true);
        if ($resf['code'] != 1) {
            throw new Exception("接口返回错误: " . $resf['message']);
        }
        return $resf;
    }

    
    public function get($endpoint, $get_params) {
        $url = $this->base_url . $endpoint . '?' . http_build_query($get_params);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // 返回响应而不是直接输出
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false); // 暂时禁用验证 todo 
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",  // 设置请求头
        ]);
        $response = curl_exec($ch);
        if ($response === false) {
            throw new Exception('请求失败: ' . curl_error($ch));
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($httpCode != 200) {
            throw new Exception('请求失败，HTTP 状态码: ' . $httpCode.' ；返回内容:'.$response);
        }
        curl_close($ch);
        $resf = json_decode($response, true);
        if ($resf['code'] != 1) {
            throw new Exception("接口返回错误: " . $resf['message']);
        }
        return $resf;
    }

}